import re
from django_redis import get_redis_connection
from rest_framework import serializers

from db.models import XlzUser, XlzUserIncomeDisburse



class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11, error_messages={'max_length': '最大长度为11位'}, required=True)
    code = serializers.CharField(max_length=4, min_length=4,
                                 error_messages={'max_length': '最大长度为4位', 'min_length': '最小长度为4位'}, required=True)

    def validate_phone(self, phone):
        if not XlzUser.objects.filter(phone=phone):
            user = XlzUser()
            user.phone = phone
            user.username = phone
            user.title_image = 'http://qiniu.tfyhyc.cn/Fu1kCbeUqbH3kd10wCOBhrX9Lj4I'
            user.save()
            user = XlzUser.objects.filter(phone=phone).first()
            gg = XlzUserIncomeDisburse()
            gg.user_id = user.id
            gg.save()
        if re.match(r'^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$', str(phone)) == None:
            raise serializers.ValidationError('手机号不合法')
        return phone

    def validate(self, attrs):
        redis = get_redis_connection("sms_code")
        code = attrs.get('code')
        phone = attrs.get('phone')
        # 从redis中取出验证码和手机号比较
        yz_code = redis.hget('sms_%s' % phone, 'para').decode()
        # 因为返回的是字符串，所以要转一下格式，
        # json.loads()，里面必须是双引号否则会报错，eval则没有这个问题
        # ss = eval(yz_code)
        # print(ss,type(ss))
        # yz_code1 = ss['vcode']
        # print(yz_code1)
        yz_phone = redis.hget('sms_%s' % phone, 'phone').decode()
        if code != yz_code or phone != yz_phone:
            raise serializers.ValidationError('手机号或验证码错误')
        return attrs


class SmsSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11, error_messages={'max_length': '最大长度为11位'})

    def validate_phone(self, phone):
        if re.match(r'^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$', str(phone)) == None:
            raise serializers.ValidationError('手机号不合法')
        return phone


class MsgSerializer(serializers.ModelSerializer):
    class Meta:
        model = XlzUser
        fields = ['id','username','title_image','phone','sex']


class ChangephoneSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11, min_length=11,error_messages={'max_length': '最大长度为11位', 'min_lenght': '最小长度11位'})

    def validate_phone(self, phone):
        if re.match(r'^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$', str(phone)) == None:
            raise serializers.ValidationError('手机号不合法')
        if XlzUser.objects.filter(phone=phone):
            raise serializers.ValidationError('手机号重复')
        return phone


class ChangeusernameSerializer(serializers.Serializer):
    username = serializers.CharField()

    def validate_username(self, username):
        if XlzUser.objects.filter(username=str(username)):
            raise serializers.ValidationError('用户名重复')
        return username



class LogoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = XlzUser
        fields = '__all__'

class ClockSerializer(serializers.ModelSerializer):
    class Meta:
        model = XlzUser
        fields = '__all__'